/*
 * @Description:游戏程序
 * @Author: maskMan
 * @LastEditTime: 2025-03-22 21:33:58
 */
import Joint from '../mongo/joint'
import { Table, TTask } from '../mongo/struct'
import { NAnimate, NTarget, NTrain } from '../types/share'
import { NDefine } from '../types/define'
import { juniorVip } from './juniorVip'
import { superVip } from './superVip'
import { util } from './util'
import { regularVip } from './regularVip'
import { animateList, detectList, trainList } from './gameList'
import Mondb from '../mongo/mondb'
import { conf } from './config'
const _hpTextList = ['1', '2', '3', '4', '5', '6']
const _hpList = [18, 15, 12, 9, 6, 3]
const _periodList = {
  p1: 7,
  p2: 15,
  p3: 21,
  p4: 30,
  p5: 60,
  p6: 90
}
const _getResUrl = function () {
  const resUrlObj = {
    video1: `${conf.resUrl}/video/`,
    video2: `${conf.resUrl}/video/`,
    litishi2: `${conf.resUrl}/video/`,
    ciji1: `${conf.resUrl}/games/`,
    jingxi1: `${conf.resUrl}/games/`,
    ciji: `${conf.resUrl}/games/`,
    jingxi: `${conf.resUrl}/games/`,
    tiaojie: `${conf.resUrl}/games/`
  }
  return resUrlObj
}
const _getTypeName = function (type) {
  const typeNameList = {
    ciji1: '刺激训练一',
    jingxi1: '精细训练一',
    video1: '视频训练一',
    video2: '视频训练二',
    litishi2: '立体视训练',
    ciji: '刺激训练',
    jingxi: '精细训练',
    tuoyizhi: '脱抑制',
    tongshi: '同时视',
    rongheshi: '融合视',
    litishi: '立体视',
    tiaojie: '调节训练'
  }
  return typeNameList[type]
}
//生成游戏训练任务
const _generateTrainTask = function (
  levelNum,
  groupList: NTrain.Type[],
  itemCount: number,
  _trainList: NTrain.GroupList
): NTrain.Member[] {
  try {
    const trainGroups: NTrain.Type[] = ['tuoyizhi', 'rongheshi', 'tongshi', 'tiaojie']
    const resultList: NTrain.Member[] = []
    for (let k = 0; k < groupList.length; k++) {
      const key = groupList[k]
      if (trainGroups.includes(key)) {
        let trainCount = Math.ceil(itemCount / groupList.length)
        if (levelNum == 1) {
          let tempArry = trainList[key].filter((v) => v.level == 'jiandan')
          let tempArry1 = util.randShuffle(trainList[key].filter((v) => v.level == 'putong'))
          for (let index = 0; index < tempArry1.length; index++) {
            tempArry.push(tempArry1[index])
            if (index >= 3) {
              break
            }
          }
          tempArry = util.randShuffle(tempArry)
          if (trainCount > tempArry.length) {
            trainCount = tempArry.length
          }
          for (let j = 0; j < trainCount; j++) {
            if (j >= tempArry.length) {
              break
            }
            tempArry[j].selectType = key
            tempArry[j].typeName = _getTypeName(key)
            resultList.push(tempArry[j])
          }
        } else if (levelNum == 2) {
          let tempArry = _trainList[key].filter((v) => v.level == 'putong')
          let tempArry1 = util.randShuffle(_trainList[key].filter((v) => v.level == 'jiandan'))
          let tempArry2 = util.randShuffle(_trainList[key].filter((v) => v.level == 'kunnan'))
          for (let index = 0; index < tempArry1.length; index++) {
            tempArry.push(tempArry1[index])
            if (index >= 3) {
              break
            }
          }
          for (let index = 0; index < tempArry2.length; index++) {
            tempArry.push(tempArry2[index])
            if (index >= 3) {
              break
            }
          }
          if (trainCount > tempArry.length) {
            trainCount = tempArry.length
          }
          tempArry = util.randShuffle(tempArry)
          for (let j = 0; j < trainCount; j++) {
            if (j >= tempArry.length) {
              break
            }
            tempArry[j].selectType = key
            tempArry[j].typeName = _getTypeName(key)
            resultList.push(tempArry[j])
          }
        } else if (levelNum == 3) {
          let tempArry = _trainList[key].filter((v) => v.level == 'kunnan')
          let tempArry1 = util.randShuffle(_trainList[key].filter((v) => v.level == 'putong'))
          let tempArry2 = util.randShuffle(_trainList[key].filter((v) => v.level == 'jiandan'))
          for (let index = 0; index < tempArry1.length; index++) {
            tempArry.push(tempArry1[index])
            if (index >= 3) {
              break
            }
          }
          for (let index = 0; index < tempArry2.length; index++) {
            tempArry.push(tempArry2[index])
            if (index >= 3) {
              break
            }
          }
          tempArry = util.randShuffle(tempArry)
          if (trainCount > tempArry.length) {
            trainCount = tempArry.length
          }
          for (let j = 0; j < trainCount; j++) {
            if (j >= tempArry.length) {
              break
            }
            tempArry[j].selectType = key
            tempArry[j].typeName = _getTypeName(key)
            resultList.push(tempArry[j])
          }
        }
      }
    }
    return resultList
  } catch (error) {
    console.log(error)
    return []
  }
}
//生成动画训练任务
const _generateAnimateTask = function (
  levelNum,
  groupList: NTrain.Type[],
  itemCount: number,
  _trainList: NTrain.GroupList,
  _animateList: NAnimate.GroupList
): NAnimate.Member[] {
  try {
    const trainGroups: NTrain.Type[] = ['ciji', 'jingxi', 'litishi']
    const resultList: NAnimate.Member[] = []
    const numObj = {
      ciji: [
        { type1: 'video1', key: 'ciji', type2: 'ciji1' },
        { type1: 'video1', key: 'ciji', type2: 'ciji1' },
        { type1: 'video1', key: 'ciji', type2: 'ciji1' }
      ],
      jingxi: [
        { type1: 'video2', key: 'jingxi', type2: 'jingxi1' },
        { type1: 'video2', key: 'jingxi', type2: 'jingxi1' },
        { type1: 'video2', key: 'jingxi', type2: 'jingxi1' }
      ],
      litishi: [
        { type1: 'litishi2', key: 'litishi', type2: 'litishi2' },
        { type1: 'litishi2', key: 'litishi', type2: 'litishi2' },
        { type1: 'litishi2', key: 'litishi', type2: 'litishi2' }
      ]
    }
    for (let k = 0; k < groupList.length; k++) {
      const key = groupList[k]
      if (trainGroups.includes(key)) {
        let levelList = []
        let trainArry = null
        let tempArry = util.randShuffle(_trainList[key].filter((v) => v.level == 'jiandan'))
        let tempArry1 = util.randShuffle(_trainList[key].filter((v) => v.level == 'putong'))
        let tempArry2 = util.randShuffle(_trainList[key].filter((v) => v.level == 'kunnan'))
        let animateArry = {}
        let gameArry = {}
        if (levelNum == 1) {
          trainArry = [...tempArry]
          for (let i = 0; i < 4; i++) {
            trainArry.push(tempArry1[i])
          }
        } else if (levelNum == 2) {
          trainArry = [...tempArry1]
          for (let i = 0; i < 4; i++) {
            trainArry.push(tempArry[i])
          }
          for (let i = 0; i < 4; i++) {
            trainArry.push(tempArry2[i])
          }
        } else if (levelNum == 3) {
          trainArry = [...tempArry2]
          for (let i = 0; i < 4; i++) {
            trainArry.push(tempArry[i])
          }
          for (let i = 0; i < 4; i++) {
            trainArry.push(tempArry1[i])
          }
        }
        trainArry = util.randShuffle(trainArry)
        let trainCount = Math.ceil(itemCount / groupList.length)
        if (levelNum == 1) {
          for (let index = 0; index < 100; index++) {
            if (index <= 40) {
              levelList.push('animate')
            } else if (index > 40 && index <= 80) {
              levelList.push('game')
            } else {
              levelList.push('train')
            }
          }
        } else if (levelNum == 2) {
          for (let index = 0; index < 100; index++) {
            if (index <= 20) {
              levelList.push('animate')
            } else if (index > 20 && index <= 60) {
              levelList.push('game')
            } else {
              levelList.push('train')
            }
          }
        } else if (levelNum == 3) {
          for (let index = 0; index < 100; index++) {
            if (index <= 10) {
              levelList.push('animate')
            } else if (index > 10 && index <= 30) {
              levelList.push('game')
            } else {
              levelList.push('train')
            }
          }
        }
        levelList = util.randShuffle(levelList)
        for (let i = 0; i < trainCount; i++) {
          const text = levelList[i]
          if (text == 'animate') {
            let typeName = numObj[key][levelNum - 1].type1
            if (i >= _animateList[typeName].length) {
              continue
            }
            if (!animateArry[typeName]) {
              animateArry[typeName] = util.randShuffle(_animateList[typeName])
            }
            const item = { ...animateArry[typeName][i] }
            item.selectType = typeName
            item.typeName = _getTypeName(typeName)
            item.completed = false
            resultList.push(item)
          } else if (text == 'game') {
            let typeName = numObj[key][levelNum - 1].type2
            if (typeName == 'litishi2') {
              if (i >= trainArry.length) {
                continue
              }
              const item = { ...trainArry[i] }
              item.selectType = key
              item.typeName = _getTypeName(key)
              item.completed = false
              resultList.push(item)
            } else {
              if (i >= _animateList[typeName].length) {
                continue
              }
              if (!gameArry[typeName]) {
                gameArry[typeName] = util.randShuffle(_animateList[typeName])
              }
              const item = { ...gameArry[typeName][i] }
              item.selectType = typeName
              item.typeName = _getTypeName(typeName)
              item.completed = false
              resultList.push(item)
            }
          } else if (text == 'train') {
            if (i >= trainArry.length) {
              continue
            }
            const item = { ...trainArry[i] }
            item.selectType = key
            item.typeName = _getTypeName(key)
            item.completed = false
            resultList.push(item)
          }
        }
      }
    }
    return util.randShuffle(resultList)
  } catch (error) {
    console.log(error)
    return []
  }
}
export const helpList: string[] = [
  `${conf.resUrl}/help/help.png`,
  'help/功能说明.mp4',
  'help/增视训练.mp4',
  'help/脱抑制训练.mp4',
  'help/视功能训练.mp4',
  'help/调节训练.mp4'
]
export const rewordWeight = {
  //时间基本权重 //1-10中间
  timeBase1: 0,
  //时间权重2 1-10中间
  timeBase2: 0,
  //得分权重 0-1000
  scoreRatio: 0,
  //时间转换得分 1000-10000之间
  scoreBase3: 0,
  //在线时间金币获得比
  coinsRatio: 0,
  //积分转换比
  pointRatio: 0
}
//获取训练营列表
export function getTrainList(vipLevel: NDefine.VipLevel, type?: NTrain.Type): NTrain.Member[] | NTrain.GroupList {
  try {
    if (!type) {
      const resultObj: NTrain.GroupList = {} as NTrain.GroupList
      const findList =
        vipLevel == '初级会员' ? juniorVip : vipLevel == '普通会员' ? regularVip : vipLevel == '高级会员' ? superVip : null
      for (const key in findList) {
        const typeName = key
        if (!resultObj[typeName]) {
          resultObj[typeName] = []
        }
        const list = trainList[typeName] || []
        for (let i = 0; i < list.length; i++) {
          const item = list[i]
          const ret = findList[key].includes(item.gamePack)
          if (ret) {
            resultObj[typeName].push(item)
          }
        }
      }
      return resultObj
    }
    let keyList
    if (vipLevel == '初级会员') {
      keyList = juniorVip[type]
    } else if (vipLevel == '普通会员') {
      keyList = regularVip[type]
    } else if (vipLevel == '高级会员') {
      keyList = superVip[type]
    } else {
      return null
    }
    const resUrlObj = _getResUrl()
    const valueList = trainList[type]
    const resultList: NTrain.Member[] = []
    for (let i = 0; i < valueList.length; i++) {
      const ret = keyList.includes(valueList[i].gamePack)
      if (ret) {
        if (valueList[i].url && valueList[i].url.length < 10) {
          valueList[i].url = `${resUrlObj[type]}${type}/${valueList[i].url}/index.html`
        }
        resultList.push(valueList[i])
      }
    }
    return resultList
  } catch (error) {
    console.log(error)
    return []
  }
}
//获取动画列表
export function getAnimateList(vipLevel: NDefine.VipLevel, type?: NAnimate.Type): NAnimate.Member[] | NAnimate.GroupList {
  try {
    if (!type) {
      const resultObj: NAnimate.GroupList = {} as NAnimate.GroupList
      const findList =
        vipLevel == '初级会员' ? juniorVip : vipLevel == '普通会员' ? regularVip : vipLevel == '高级会员' ? superVip : null
      for (const key in findList) {
        const typeName = key
        if (!resultObj[typeName]) {
          resultObj[typeName] = []
        }
        const list = animateList[typeName] || []
        for (let i = 0; i < list.length; i++) {
          const item = list[i]
          const ret = findList[key].includes(item.gamePack)
          if (ret) {
            resultObj[typeName].push(item)
          }
        }
      }
      return resultObj
    }
    let keyList
    if (vipLevel == '初级会员') {
      keyList = juniorVip[type]
    } else if (vipLevel == '普通会员') {
      keyList = regularVip[type]
    } else if (vipLevel == '高级会员') {
      keyList = superVip[type]
    } else {
      return null
    }
    const valueList = animateList[type]
    const resultList: NAnimate.Member[] = []
    const resUrlObj = _getResUrl()
    for (let i = 0; i < valueList.length; i++) {
      const ret = keyList.includes(valueList[i].gamePack)
      if (ret) {
        if (valueList[i].actionKind == 'animate' && valueList[i].url.length < 10) {
          valueList[i].url = `${resUrlObj[type]}${type}/${valueList[i].url}`
        } else if (valueList[i].actionKind == 'game' && valueList[i].url && valueList[i].url.length < 10) {
          valueList[i].url = `${resUrlObj[type]}${type}/${valueList[i].url}/index.html`
        }
        resultList.push(valueList[i])
      }
    }
    return resultList
  } catch (error) {
    console.log(error)
    return []
  }
}
//获取侦探列表
export function getDetectList(type: 'shigong', vipLevel: NDefine.VipLevel): NTrain.Member[] {
  try {
    let keyList
    if (vipLevel == '初级会员') {
      keyList = juniorVip[type]
    } else if (vipLevel == '普通会员') {
      keyList = regularVip[type]
    } else if (vipLevel == '高级会员') {
      keyList = superVip[type]
    } else {
      return null
    }
    const valueList = detectList
    const resultList: NTrain.Member[] = []
    for (let i = 0; i < valueList.length; i++) {
      const ret = keyList.includes(valueList[i].gamePack)
      if (ret) {
        resultList.push(valueList[i])
      }
    }
    return resultList
  } catch (error) {
    console.log(error)
    return []
  }
}
//创建小目标数据
export function createTargetData(createData: NTarget.Create, age: number) {
  try {
    const totalTime = createData.itemCount * createData.limitTime * 60
    const itemData: NTarget.ItemData = {
      dayCount: _periodList[createData.period],
      hpCount: _hpList[_hpTextList.findIndex((v) => v == createData.level)],
      levelNum: age <= 4 ? 1 : age >= 8 ? 3 : 2,
      totalTime: totalTime,
      completed: false,
      groupList: createData.typeList,
      limitTime: createData.limitTime,
      itemCount: createData.itemCount
    }
    const { dayCount } = itemData
    const itemList: NTarget.Task[] = []
    for (let i = 0; i < dayCount; i++) {
      const dayData: NTarget.Task = {
        dayIndex: i + 1,
        markStatus: i == 0 ? 0 : 1,
        star: 0,
        score: 0,
        taskList: [],
        reword: 0,
        restTime: totalTime,
        actionDate: null,
        completed: false
      }
      itemList.push(dayData)
    }
    return { taskList: itemList, itemData }
  } catch (error) {
    console.error('createTargetData', error, createData, age)
    return null
  }
}
//检测任务
export async function checkAndGetTaskData(account: string, vipLevel: NDefine.VipLevel): Promise<Partial<TTask>> {
  try {
    const targetData = await Joint.getTargetData(account, 'itemData', 'taskList', 'createData')
    if (!targetData) {
      return Promise.resolve(null)
    }
    const { taskList, itemData, createData } = targetData
    if (taskList) {
      if (!taskList.length || !taskList.find((v) => v.markStatus >= 0)) {
        return Promise.resolve({ taskList, itemData })
      }
      const taskData = taskList.find((v) => v.markStatus == 0)
      if (taskData && taskData.taskList?.length > 0) {
        return Promise.resolve({ taskList, itemData })
      }
      const resUrlObj = _getResUrl()
      const currDay = util.currDay()
      if (createData && !taskList.find((v) => v.actionDate == currDay)) {
        const lastIndex = taskList.findIndex((v) => v.markStatus >= 0)
        if (lastIndex >= 0) {
          const taskArry: NTarget.TaskData[] = []
          const _trainList = getTrainList(vipLevel) as NTrain.GroupList
          const _animateList = getAnimateList(vipLevel) as NAnimate.GroupList
          const step1 = _generateTrainTask(itemData.levelNum, createData.typeList, createData.itemCount, _trainList)
          const step2 = _generateAnimateTask(
            itemData.levelNum,
            createData.typeList,
            createData.itemCount,
            _trainList,
            _animateList
          )
          const step = [...step1, ...step2]
          let count = 0
          if (step.length == 0) {
            return Promise.resolve(null)
          }
          for (let index = 0; index < createData.itemCount; index++) {
            if (count >= step.length) {
              count = 0
            }
            if (step[count]['actionKind']) {
              const actype = step[count].selectType
              if (step[count]['actionKind'] == 'animate' && step[count].url.length < 10) {
                step[count].url = `${resUrlObj[actype]}${actype}/${step[count].url}`
              } else if (step[count]['actionKind'] == 'game' && step[count].url.length < 10) {
                step[count].url = `${resUrlObj[actype]}${actype}/${step[count].url}/index.html`
              }
              taskArry.push({
                id: index + 1,
                animateData: step[count] as any
              })
            } else {
              const actype = step[count].selectType
              if (step[count].url && step[count].url.length < 10) {
                step[count].url = `${resUrlObj[actype]}${actype}/${step[count].url}/index.html`
              }
              taskArry.push({
                id: index + 1,
                trainData: step[count] as any
              })
            }
            count++
          }
          taskList[lastIndex].actionDate = currDay
          taskList[lastIndex].markStatus = 0
          taskList[lastIndex].taskList = taskArry
          const result = await Joint.createTargetData(account, { taskList })
          if (result) {
            return Promise.resolve({ taskList: result.taskList, itemData })
          }
        }
      } else {
        return Promise.resolve({ taskList, itemData })
      }
    }
    return Promise.resolve(null)
  } catch (error) {
    console.log('checkAndGetTaskData', error)
  }
}
//获取权重得分
export function getWeightScore(score, errCount, fixTime, cTime): any {
  try {
    if (score == -1) {
      score = 0
    }
    if (errCount > 0) {
      errCount--
    }
    const costTime = Math.floor(cTime / 60000)
    const errScore = rewordWeight.timeBase1 * 240 - errCount * 10 * rewordWeight.timeBase1
    const constRatio = costTime / 240
    const timeScore = rewordWeight.timeBase2 * 480 * constRatio
    let scoreValue = (score / (costTime * rewordWeight.scoreBase3)) * fixTime
    if (scoreValue == Infinity || Number.isNaN(scoreValue)) {
      scoreValue = 0
    }
    const total = Math.floor(scoreValue + timeScore + errScore * constRatio)
    return Number.isNaN(total) ? 0 : total
  } catch (error) {
    return 0
  }
}
//获取更新权重
export async function getWeightData() {
  const result = await Mondb.findOneData(Table.weight, { WID: 1 })
  if (result) {
    for (const key in result) {
      if (result[key] != undefined || result[key] != null) {
        rewordWeight[key] = result[key]
      }
    }
  }
}
